//
//  ChatBase.m
//  ChildHoodStemp
//
//  Created by 日东 罗 on 13-8-29.
//
//

#import "MBProgressHUD.h"
#import "IMSearchChatRecordController.h"
#import "Reachability.h"
#import "ChatBase.h"
#import "ChatMessageListCell.h"
#import "UIUtil.h"
#import "ChildHoodMessage.h"
#import "ChatMessageListCellData.h"
#import "Snsp.pb.h"
#import "ChildHoodRoom.h"
#import "CHChatRoomBase.h"
#import "ChildHoodUser.h"
#import "MessageDao.h"
#import "CAccountMgr.h"
#import "CXmppMgr.h"
#import "CMessageMgr.h"
#import "CMessageModel.h"
#import "CContactMgr.h"
#import "CContactModel.h"
#import "CXmppRequestMgr.h"
#import "MJRefresh.h"
#import "CUserSettingModel.h"
#import "CUserSettingMgr.h"
#import "JKAlertDialog.h"
#import "ModifyGuesturePasswordController.h"
//#import "CAccountMgr.h"
//#import "CAccountModel.h"
#import "CFolderMgr.h"
#import "CGroupMgr.h"
#import "CGroupModel.h"
#import "GroupMenberCell.h"
#import "UIImageView+WebCache.h"
#import "NSArray+PinYin.h"
#import "CDepartmentModel.h"
#import "CDepartmentMgr.h"
#import "GroupMemberDetailVC.h"
#import "SettingNormalCell.h"
#import "CMessageDraft.h"
#import "CMessageDraftMgr.h"
#import "MBProgressHUD+WZ.h"
#import "LoginViewController.h"
#import "CCHatRecordCell.h"
#import "NSData+CBExtension.h"
#import "IMSearchDisplayController.h"
#import "UIBarButtonItem+category.h"
#import "EFengChatListView.h"
#import "WZSearchController.h"
#import "CMessageFrame.h"
#import "EFengChatBaseView.h"
#import "EFengContactButton.h"
#import "WZSearchMessageResultController.h"
#import "CCompany.h"
#import "CCompanyMgr.h"
#import "FingerprintIdentificationViewController.h"
//间距
#define IOS8 ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0 )
#define INSETS 8
#define HEAD_SIZE 50.f
#define kCellBaseTag            10000

#define buttonCount 3


static const void * const ChatBaseDispatchQueueSpecificKey = &ChatBaseDispatchQueueSpecificKey;

@interface ChatBase ()<UIActionSheetDelegate, UISearchBarDelegate, EFengChatListViewDelegate, EFengChatBaseViewDelegate, UIScrollViewDelegate>
{
    NSMutableArray          *_listData;
    NSMutableDictionary     *_roomInfoRequestDic;
    BOOL                    _refreshable;
    BOOL                    _canSelected;
    NSMutableDictionary     *_roomDic;
    NSTimer                 *timer;
    UISearchBar *_searchBar;
    NSMutableArray*         _groupArray;
    int _unreadNoticeNum;
    BOOL isNetconnect;
    UISearchDisplayController *_searchDisplayController;
    dispatch_queue_t  _chatBaseQueen;
}

StrongProperty NSLock *lock;
StrongProperty  UISearchBar *searchBar;
StrongProperty WZSearchController *searchController;

StrongProperty UIScrollView *scrollView;

StrongProperty EFengChatBaseView *AllBaseView;
StrongProperty EFengChatBaseView *WorkBaseView;
StrongProperty EFengChatBaseView *contactBaseView;
StrongProperty UIView *topView;
StrongProperty NSMutableArray *MessageGroupSearchArray;
WeakProperty EFengContactButton *selectedButton;
WeakProperty UIView *noMessageView;




@property(strong, nonatomic)NSDictionary *upDateDic;
//-(void)roominfoEvent:(NSNotification*)notification;
//-(void)msgRefreshEvent:(NSNotification *)notification;
@property (nonatomic ,strong) CGroupMgr *groupMgr;
@property (nonatomic, strong) CMessageDraftMgr *draftMgr;
@property (nonatomic, strong) CMessageMgr *messageMgr;


StrongProperty EFengChatListView *chatList;

@end

@implementation ChatBase

-(void)dealloc
{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:K_XMPPRECEIVEMESSAGE object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:K_XMPPDIDSENDMESSAGE object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:K_XMPPFAILEDRECEIVEMESSAGE object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:K_XMPPUPDATEMESSAGERECORD object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:K_XMPPLOGINRESULT object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:K_XMPPUPDATEMESSAGESTATUES object:nil];
    //     NSLog(@"ChatBase dealloc");
    
}
-(NSMutableArray *)MessageGroupSearchArray
{
    if (_MessageGroupSearchArray == nil) {
        _MessageGroupSearchArray = [NSMutableArray array];
    }
    return _MessageGroupSearchArray;
}
-(void)handleData:(NSArray*)messages
{
    [_listData removeAllObjects];
    [messages enumerateObjectsUsingBlock:^(id message, NSUInteger idx, BOOL *stop) {
        ChatMessageListCellData *data = [[ChatMessageListCellData alloc] init];
        
        if ([message isKindOfClass:[CMessageDraft class]]) {
            CMessageDraft *messageDraft = (CMessageDraft *)message;
            data.messageIndex = messageDraft.MessageIndex;
            if (messageDraft.GroupId.length > 3) {
                data.FriendUserId = messageDraft.MineUserId;
                data.senderName = messageDraft.FriendUserName;
                data.groupType = messageDraft.yuLiuZiduan2;
                data.headImageUri = [[CXmppRequestMgr shareInstance] DownHeadFileWithContact:messageDraft.MineUserId];
                if ([[[CFolderMgr shareInstance].accMgr getRecentlyLoginAccount].userId isEqualToString:messageDraft.MineUserId]) {
                    data.content = [NSString stringWithFormat:@"[草稿]%@",messageDraft.MessageContent];
                } else {
                    if (messageDraft.MessageSendedStatus == kMessageUserMute) {
                        data.content = [NSString stringWithFormat:@"%@:[草稿]%@",messageDraft.MineUserName,messageDraft.MessageContent];
                    } else {
                        data.content = [NSString stringWithFormat:@"%@:%@",messageDraft.MineUserName,messageDraft.MessageContent];
                    }
                }
            } else {
                data.FriendUserId = messageDraft.FriendUserId;
                data.isKefu = [[[CContactMgr alloc] init] isKefuContactWithUserId:data.FriendUserId];
                data.headImageUri = [[CXmppRequestMgr shareInstance] DownHeadFileWithContact:messageDraft.FriendUserId];
                if (messageDraft.MessageSendedStatus == kMessageUserMute) {
                    data.content = [NSString stringWithFormat:@"[草稿]%@",messageDraft.MessageContent];
                } else {
                    data.content = messageDraft.MessageContent;
                }
                
                data.senderName = messageDraft.FriendUserName;
                if ([messageDraft.FriendUserId isEqualToString:messageDraft.MineUserId]) {
                    data.senderName = @"我的电脑";
                }
            }
            data.MineUserId = messageDraft.MineUserId;
            data.GroupId = messageDraft.GroupId;
            NSDate *date = [NSDate dateWithTimeIntervalSince1970:messageDraft.TimeStamp.longLongValue / 1000.0];
            data.sendTime = [UIUtil timeForMessageListStyle:date];
            
            if (messageDraft.GroupId.length > 3) {
                data.unreadNumber = [[[CMessageMgr alloc] init] loadGroupUnReadCountWithGroupdId:messageDraft.GroupId];
            } else {
                data.unreadNumber = [[[CMessageMgr alloc] init] loadUnReadCountWithMineUserId:messageDraft.MineUserId FriendUserId:messageDraft.FriendUserId];
                
            }
            
            if ([messageDraft.MessageType isEqualToString:@"text"]) {
                data.messageType = SNSPMaterialTypeKMessage;
            } else if ([messageDraft.MessageType isEqualToString:@"voice"]) {
                data.messageType = SNSPMaterialTypeKAudio;
            } else if ([messageDraft.MessageType isEqualToString:@"image"]) {
                data.messageType = SNSPMaterialTypeKImage;
            } else if ([messageDraft.MessageType isEqualToString:@"file"]) {
                data.messageType = SNSPMaterialTypeKFile;
            } else if ([messageDraft.MessageType isEqualToString:@"video"]){
                data.messageType = SNSPMaterialTypeKVideo;
            } else if ([messageDraft.MessageType isEqualToString:@"redpacket"]){
                 data.messageType = SNSRedPacket;
            }
            data.messageStatus = messageDraft.MessageSendedStatus;
            
        } else if ([message isKindOfClass:[CMessageModel class]]) {
            CMessageModel *obj = (CMessageModel *)message;
            data.messageIndex = obj.MessageIndex;
            if ([obj.MessageType isEqualToString:@"text"]) {
                data.messageType = SNSPMaterialTypeKMessage;
            } else if ([obj.MessageType isEqualToString:@"voice"]) {
                data.messageType = SNSPMaterialTypeKAudio;
            } else if ([obj.MessageType isEqualToString:@"image"]) {
                data.messageType = SNSPMaterialTypeKImage;
            } else if ([obj.MessageType isEqualToString:@"file"]) {
                data.messageType = SNSPMaterialTypeKFile;
            } else if ([obj.MessageType isEqualToString:@"shke"]){
                data.messageType = SNSPMaterialTypeKMessage;
            }else if ([obj.MessageType isEqualToString:@"video"]){
                data.messageType = SNSPMaterialTypeKVideo;
            }else if ([obj.MessageType isEqualToString:@"redpacket"]){
                data.messageType = SNSRedPacket;
            }
            
            if (obj.GroupId.length > 3) {
                data.groupType = obj.yuLiuZiduan2;
                data.FriendUserId = obj.MineUserId;
                data.senderName = obj.FriendUserName;
                data.headImageUri = [[CXmppRequestMgr shareInstance] DownHeadFileWithContact:obj.MineUserId];
                if ([[[CFolderMgr shareInstance].accMgr getRecentlyLoginAccount].userId isEqualToString:obj.MineUserId]) {
                    if (data.messageType == SNSPMaterialTypeKMessage) {
                        data.content = obj.MessageContent;
                    } else if (data.messageType == SNSPMaterialTypeKImage)
                    {
                        data.content = @"[图片]";
                    } else if (data.messageType == SNSPMaterialTypeKAudio) {
                        data.content = @"[语音]";
                    }
                    else if (data.messageType == SNSPMaterialTypeKVideo){
                        data.content = @"[视频]";
                        
                    }else  if (data.messageType == SNSPMaterialNotice) {
                        data.content = @"[系统通知]";
                        
                    } else  if (data.messageType == SNSPMaterialTypeKFile) {
                        data.content = @"[文件]";
                    } else if (data.messageType == SNSRedPacket){
                        data.content = [NSString stringWithFormat:@"%@%@",@"[e蜂红包]",obj.MessageContent];
                    }
                    
                } else {
                    if (data.messageType == SNSPMaterialTypeKMessage) {
                        
                        data.content = [NSString stringWithFormat:@"%@:%@",obj.MineUserName,obj.MessageContent];
                    } else if (data.messageType == SNSPMaterialTypeKImage)
                    {
                        data.content = [NSString stringWithFormat:@"%@:[图片]",obj.MineUserName];
                    } else if (data.messageType == SNSPMaterialTypeKAudio) {
                        data.content = [NSString stringWithFormat:@"%@:[语音]",obj.MineUserName];
                    } else  if (data.messageType == SNSPMessageTypeKNoticeType) {
                        
                    } else  if (data.messageType == SNSPMaterialTypeKFile) {
                        data.content = [NSString stringWithFormat:@"%@:[文件]",obj.MineUserName];
                    } else if (data.messageType == SNSPMaterialTypeKVideo){
                         data.content = [NSString stringWithFormat:@"%@:[视频]",obj.MineUserName];
                    }else if (data.messageType == SNSRedPacket){
                        data.content = [NSString stringWithFormat:@"%@%@",@"[e蜂红包]",obj.MessageContent];
                    }
                    
                }
            } else {
                data.FriendUserId = obj.FriendUserId;
                data.isKefu = [[[CContactMgr alloc] init] isKefuContactWithUserId:data.FriendUserId];
                data.headImageUri = [[CXmppRequestMgr shareInstance] DownHeadFileWithContact:obj.FriendUserId];
                if (data.messageType == SNSPMaterialTypeKMessage) {
                    
                    data.content = obj.MessageContent;
                } else if (data.messageType == SNSPMaterialTypeKImage)
                {
                    data.content = @"[图片]";
                } else if (data.messageType == SNSPMaterialTypeKAudio) {
                    data.content = @"[语音]";
                } else  if (data.messageType == SNSPMaterialTypeKVideo) {
                     data.content = @"[视频]";
                }else  if (data.messageType == SNSPMaterialNotice) {
                    
                }  else  if (data.messageType == SNSPMaterialTypeKFile) {
                    data.content = @"[文件]";
                } else if (data.messageType == SNSPMaterialTypeKVideo){
                    data.content = @"[视频]";
                }else if (data.messageType == SNSRedPacket){
                    data.content = [NSString stringWithFormat:@"%@%@",@"[e蜂红包]",obj.MessageContent];
                }
                
                data.senderName = obj.FriendUserName;
                if ([obj.FriendUserId isEqualToString:obj.MineUserId]) {
                    data.senderName = @"我的电脑";
                }
                
            }
            data.MineUserId = obj.MineUserId;
            data.FriendJid = obj.FriendJid;
            data.MineJid = obj.MineJid;
            data.GroupId = obj.GroupId;
            data.isRead = obj.ReadStatus;
            NSDate *date = [NSDate dateWithTimeIntervalSince1970:obj.TimeStamp.longLongValue / 1000.0];
            
            data.sendTime = [UIUtil timeForMessageListStyle:date];
            
            if (obj.GroupId.length > 3) {
                data.unreadNumber = [[[CMessageMgr alloc] init] loadGroupUnReadCountWithGroupdId:obj.GroupId];
            } else {
                data.unreadNumber = [[[CMessageMgr alloc] init] loadUnReadCountWithMineUserId:obj.MineUserId FriendUserId:obj.FriendUserId];
                
            }
            
            data.messageStatus = obj.MessageSendedStatus;
            //        data.messageStatus = obj.ReadStatus;
            
        }
        [_listData addObject:data];
     
    }];
    //        CContactModel *contact = [[[CContactMgr alloc] init] loadContactWithUserId:obj.FriendUserId];
 
}

- (UIView *)topView
{
    if (_topView == nil) {
        _topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, HARDWARE_SCREEN_WIDTH, 44.0f)];
        _topView.backgroundColor = WhiteColor;
    }
    return _topView;
}


- (EFengChatBaseView *)AllBaseView
{
    if (_AllBaseView == nil) {
        _AllBaseView = [[EFengChatBaseView alloc] init];
        _AllBaseView.eFengChatBaseViewDelegate = self;
    }
    return _AllBaseView;
}

- (EFengChatBaseView *)WorkBaseView
{
    if (_WorkBaseView == nil) {
        _WorkBaseView = [[EFengChatBaseView alloc] init];
        _WorkBaseView.eFengChatBaseViewDelegate = self;
    }
    return _WorkBaseView;
}

- (EFengChatBaseView *)contactBaseView
{
    if (_contactBaseView == nil) {
        _contactBaseView = [[EFengChatBaseView alloc] init];
        _contactBaseView.eFengChatBaseViewDelegate = self;
    }
    return _contactBaseView;
}

- (UIScrollView *)scrollView
{
    if (_scrollView == nil) {
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.backgroundColor = ClearColor;
        _scrollView.pagingEnabled = YES;
        _scrollView.bounces = NO;
        _scrollView.delegate = self;
        _scrollView.scrollEnabled = NO;
    }
    return _scrollView;
}


- (EFengChatListView *)chatList
{
    if (_chatList == nil) {
        _chatList = [[EFengChatListView alloc] initWithFrame:CGRectZero];
        _chatList.chatListDelegate = self;
        [self.view addSubview:_chatList];
    }
    return _chatList;
}

//- (void)handlePathWithPath:(NSString *)path
//{
//
//    NSArray *array = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:nil];
//    for (NSString *subPath in array) {
//        NSString *filePath = [path stringByAppendingPathComponent:subPath];
//        BOOL isdir = NO;
//        [[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:&isdir];
//        if (isdir){
//
//            [self handlePathWithPath:filePath];
//        } else {
//
//            CFileModel *fileModel = [[CFileModel alloc] init];
//            fileModel.FileName = filePath.lastPathComponent;
//            fileModel.LocalFilePath = filePath;
//            fileModel.isDir = NO;
//            NSLog(@"%@",filePath);
//
//        }
//    }
//
//}
//

- (void)viewDidLoad
{
    [super viewDidLoad];
    isNetconnect=YES;
    
    _chatBaseQueen = dispatch_queue_create([[NSString stringWithFormat:@"ChatBase.%@", self] UTF8String], NULL);
    dispatch_queue_set_specific(_chatBaseQueen, ChatBaseDispatchQueueSpecificKey, (__bridge void *)self, NULL);
    
    self.lock = [[NSLock alloc] init];
    if (IsIOS7) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    self.groupMgr = [[CGroupMgr alloc] init];
    self.draftMgr = [[CMessageDraftMgr alloc] init];
    self.messageMgr = [[CMessageMgr alloc] init];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotice) name:K_XMPPRECEIVEMESSAGE object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotice) name:K_XMPPDIDSENDMESSAGE object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotice) name:K_XMPPFAILEDRECEIVEMESSAGE object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotice) name:K_XMPPUPDATEMESSAGESTATUES object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotice) name:K_XMPPUPDATEMESSAGERECORD object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(chatBaseNetChanged:) name: K_XMPPLOGINRESULT object: nil];
    //    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadListMessage) name:K_XMPPRECEIVEMESSAGE object:nil];
    _refreshable = YES;
    //    [self.navigationItem setLeftItemWithTarget:self action:nil image:@"back_bar_button.png" selectedImageName:@"back_bar_button_tapped.png" text:nil disabled:@"back_bar_button_disabled.png"];    // Do any additional setup after loading the view.
    //    [self addTimer];
    
    [self.view setBackgroundColor:RGBCOLOR(243, 243, 243)];
    
    // Do any additional setup after loading the view.
    
    //    UIView* vi = [UIUtil getAViewWithSize:CGSizeMake(HARDWARE_SCREEN_WIDTH, 30) backGroundColor:CommonColor];
    //    [vi setCenter:CGPointMake(HARDWARE_SCREEN_WIDTH/2, -15)];
    //    [self.view addSubview:vi];
    [self.navigationItem setNewTitleCenter:@"消息"];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem BarButtonItemWithImageName:@"btn-more" title:nil target:self sel:@selector(messageMenu) titleFont:Font16 titleColor:WhiteColor];
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem BarButtonItemWithImageName:@"btn-search" title:nil target:self sel:@selector(search) titleFont:Font18 titleColor:WhiteColor];
    
    
    self.topView.frame = CGRectMake(0, 0, HARDWARE_SCREEN_WIDTH, 44.0f);
    [self setupTopView];
    [self.view addSubview:self.topView];
    self.topView.hidden = YES;
    
    UIView *line = [[UIView alloc] init];
    line.hidden = YES;
    line.frame = CGRectMake(0, self.topView.height - 0.5, HARDWARE_SCREEN_WIDTH, 0.5f);
    line.backgroundColor = RGBCOLOR(212, 212, 212);
    [self.topView addSubview:line];
    
    
    self.scrollView.frame = CGRectMake(0, 0, HARDWARE_SCREEN_WIDTH, HARDWARE_SCREEN_HEIGHT - 64.0f - 49.0f);
    self.scrollView.contentSize = CGSizeMake(HARDWARE_SCREEN_WIDTH * buttonCount, 0);
    [self.view addSubview:self.scrollView];
 
    
    
    
    self.AllBaseView.frame = CGRectMake(0, 0, HARDWARE_SCREEN_WIDTH, self.scrollView.height);
    [self.scrollView addSubview:self.AllBaseView];
 
    
    self.contactBaseView.frame = CGRectMake(CGRectGetMaxX(self.AllBaseView.frame),0 , HARDWARE_SCREEN_WIDTH, self.scrollView.height);
    [self.scrollView addSubview:self.contactBaseView];
    
    
    self.WorkBaseView.frame = CGRectMake(CGRectGetMaxX(self.contactBaseView.frame), 0, HARDWARE_SCREEN_WIDTH, self.scrollView.height);
    [self.scrollView addSubview:self.WorkBaseView];
    UIView *noticeView = [[UIView alloc]initWithFrame:self.view.bounds];
    [self.view addSubview:noticeView];
    self.noMessageView = noticeView;
    
    //搜索相关
    _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
    _searchBar.backgroundImage = [UIImage imageNamed:@"BG-search"];
    //test 联系人搜索
    _searchBar.placeholder = @"搜索";
    _searchBar.delegate = self;
    _searchBar.hidden = YES;
    // 添加 searchbar 到 headerview
    [self.view addSubview:_searchBar];
    
    _searchController = [[WZSearchController alloc] initWithSearchBar:_searchBar contentsController:self];
    
    
 
    UIImageView *imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"no-message"]];
    imageView.center = CGPointMake(noticeView.center.x, noticeView.center.y - 64);
    [noticeView addSubview:imageView];
    UILabel *label = [[UILabel alloc]init];
    label.frame = CGRectMake(0, 0, 100, 40);
    label.textColor = [UIUtil colorWithHexString:@"#b5b5b5" withAlpha:1];
    label.textAlignment = NSTextAlignmentCenter ;
    label.font = [UIFont systemFontOfSize:12];
    label.center = CGPointMake(imageView.center.x,CGRectGetMaxY(imageView.frame)+22);
    label.text = @"暂时没有新消息";
    [self.noMessageView addSubview:label];
    //    bug 6340
    
    //    //////////////////////////////////////////////////////
    
    MJRefreshNormalHeader *header1 = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(reconnectNet)];
    [header1 setTitle:@"下拉重连" forState:MJRefreshStateIdle];
    [header1 setTitle:@"下拉进行重连" forState:MJRefreshStatePulling];
    [header1 setTitle:@"连接中 ..." forState:MJRefreshStateRefreshing];
    self.AllBaseView.tableView.header = header1;
    
    MJRefreshNormalHeader *header2 = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(reconnectNet)];
    [header2 setTitle:@"下拉重连" forState:MJRefreshStateIdle];
    [header2 setTitle:@"下拉进行重连" forState:MJRefreshStatePulling];
    [header2 setTitle:@"连接中 ..." forState:MJRefreshStateRefreshing];
    self.contactBaseView.tableView.header = header2;
    
    MJRefreshNormalHeader *header3 = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(reconnectNet)];
    [header3 setTitle:@"下拉重连" forState:MJRefreshStateIdle];
    [header3 setTitle:@"下拉进行重连" forState:MJRefreshStatePulling];
    [header3 setTitle:@"连接中 ..." forState:MJRefreshStateRefreshing];
    self.WorkBaseView.tableView.header = header3;
    
    
    _listData = [[NSMutableArray alloc] initWithCapacity:1];
    
    _refreshable = YES;
    _canSelected = NO;
    
    
    self.chatList.chatListViewArray = @[@"将消息置为已读"];
    [self.view bringSubviewToFront:self.chatList];

    
}



- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
    if (IsIOS7) {
        [self.navigationController.navigationBar setBarTintColor:RGBCOLOR(44, 170, 253)];
    } else {
        [self.navigationController.navigationBar setTintColor:RGBCOLOR(44, 170, 253)];
    }
    [self topListBtnClick:self.selectedButton];
  
    
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    UINavigationController *nav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    
    
    if ([USER_DEFAULT boolForKey:is_ForgetGuesturePassword] == YES) {
        JKAlertDialog *alert = [[JKAlertDialog alloc]initWithTitle:nil message:@"旧的手势密码已清除，是否重新设置?"];
        [alert addButton:Button_OK withTitle:@"重新设置" handler:^(JKAlertDialogItem *item) {
            [USER_DEFAULT setBool:NO forKey:is_ForgetGuesturePassword];
            [USER_DEFAULT synchronize];
            
            nav.navigationBarHidden = NO;
            self.navigationController.navigationBarHidden = YES;
            ModifyGuesturePasswordController *vc = [[ModifyGuesturePasswordController alloc] init];
            [nav pushViewController:vc animated:YES];
        }];
        
        [alert addButton:Button_CANCEL withTitle:@"取消" handler:^(JKAlertDialogItem *item) {
            
            [USER_DEFAULT setBool:NO forKey:is_ForgetGuesturePassword];
            [USER_DEFAULT setBool:NO forKey:is_GuseturePassword];
            [USER_DEFAULT synchronize];
            
        }];
        [alert show];
        
    }
    
    
    
}



- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if (_searchController.active) {
        [_searchController setActive:NO];
    }
}

-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
    
}


- (void)setupTopView
{
    
    
    EFengContactButton *allBtn = [self addbuttonWithTitle:@"全部" imageName:@"icon-organization"];
    allBtn.tag = 300001;
    [self.topView addSubview:allBtn];
    self.selectedButton = allBtn;
    
    EFengContactButton *groupBtn = [self addbuttonWithTitle:@"联系人" imageName:@"icon-group1"];
    groupBtn.tag = 300002;
    [self.topView addSubview:groupBtn];
    
    EFengContactButton *discussBtn = [self addbuttonWithTitle:@"办公" imageName:@"icon-comment"];
    discussBtn.tag = 300003;
    [self.topView addSubview:discussBtn];
    
    
    
    CGFloat buttwidthGap = (HARDWARE_SCREEN_WIDTH - (allBtn.width + groupBtn.width + discussBtn.width)) / 3.0f;
    allBtn.frame = CGRectMake(0, 0, allBtn.width + buttwidthGap, self.topView.height);
    groupBtn.frame = CGRectMake(CGRectGetMaxX(allBtn.frame), 0, groupBtn.width + buttwidthGap, self.topView.height);
    discussBtn.frame = CGRectMake(CGRectGetMaxX(groupBtn.frame), 0, discussBtn.width + buttwidthGap, self.topView.height);
}

- (EFengContactButton *)addbuttonWithTitle:(NSString *)title imageName:(NSString *)imageName
{
    EFengContactButton *button = [EFengContactButton buttonWithType:UIButtonTypeCustom];
    button.backgroundColor = ClearColor;
    //    [button setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    [button setTitle:title forState:UIControlStateNormal];
    button.titleLabel.font = Font16;
    //    button.contentEdgeInsets = UIEdgeInsetsMake(5.0f, 0, 0, 0);
    [button setTitleColor:BlackColor forState:UIControlStateNormal];
    
    button.width = [title sizeWithFont:Font16 maxSize:CGSizeMake(MAXFLOAT, MAXFLOAT)].width;
    [button setTitleColor:RGBCOLOR(44, 170, 253) forState:UIControlStateSelected];
    [button addTarget:self action:@selector(topListBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    button.backgroundColor = ClearColor;
    return button;
}

- (void)topListBtnClick:(EFengContactButton *)button
{
    self.selectedButton.selected = NO;
    button.selected = YES;
    self.selectedButton = button;
    
    switch (button.tag) {
        case 300001:
        {
            dispatch_block_t block = ^{
                [self loadListMessage];
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (_listData.count > 0) {
                        self.noMessageView.hidden = YES;
                    }
                    self.AllBaseView.messages = [_listData copy];
                    
                    [self.scrollView setContentOffset:CGPointMake(0, 0)];
                });
            };
            
            
            if (dispatch_get_specific(ChatBaseDispatchQueueSpecificKey)){
                block();
            }
            else {
                dispatch_async(_chatBaseQueen, block);
                
            }
            
            
            
            
        }
            break;
        case 300002:
        {
            dispatch_block_t block = ^{
                [self loadListMessage];
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.contactBaseView.messages = _listData;
                    [self.scrollView setContentOffset:CGPointMake(HARDWARE_SCREEN_WIDTH, 0)];
                });
            };
            
            if (dispatch_get_specific(ChatBaseDispatchQueueSpecificKey))
                block();
            else
                dispatch_barrier_async(_chatBaseQueen, block);
            
            
            
            
            
            
            
            
        }
            break;
        case 300003:
        {
            dispatch_block_t block = ^{
                [self loadListMessage];
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.WorkBaseView.messages = _listData;
                    [self.scrollView setContentOffset:CGPointMake(HARDWARE_SCREEN_WIDTH * 2, 0)];
                    
                });
            };
            
            if (dispatch_get_specific(ChatBaseDispatchQueueSpecificKey))
                block();
            else
                dispatch_async(_chatBaseQueen, block);
        }
            break;
            
        default:
            break;
    }
    
}

#pragma mark uiscrollDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSInteger btnTag =  self.selectedButton.tag;
    if (scrollView.contentOffset.x == HARDWARE_SCREEN_WIDTH * 2 && btnTag == 300003) {
        return;
        
    }
    
    if (scrollView.contentOffset.x == 0 && btnTag == 300001) {
        return;
    }
    self.selectedButton.selected = NO;
    btnTag = (NSInteger)(scrollView.contentOffset.x / HARDWARE_SCREEN_WIDTH) % 3 + 300001;
    EFengContactButton *btn = (EFengContactButton *)[self.topView viewWithTag:btnTag];
    [self topListBtnClick:btn];
}


- (void)messageMenu
{
    UIButton *btn = (UIButton *)self.navigationItem.rightBarButtonItem.customView;
    btn.selected = !btn.selected;
    if (btn.selected) {
        [self.chatList showChatListView];
        
    } else {
        
        [self.chatList hieChatListView];
    }
    
}
- (void)loadNewestMessage
{
    
}

#pragma mark 搜索相关
// bug 8640 fixed by lixu
- (void)search
{
    //    [self.searchDisplayController setActive:YES animated:NO];
    [self.searchBar becomeFirstResponder];
    __weak ChatBase *weakSelf = self;
    
    [weakSelf.searchController setCellForRowAtIndexPathCompletion:^UITableViewCell *(UITableView *tableView, NSIndexPath *indexPath) {
        
        NSArray *searchArray = weakSelf.searchController.searchSectionListArray[indexPath.section];
        id obj = searchArray[indexPath.row];
        if ([obj isKindOfClass:[NSMutableArray class]])
        {
            NSMutableArray *messageArray = (NSMutableArray*)obj;
            if (messageArray.count == 1) {
                CMessageFrame *messageFrame = messageArray.lastObject;
                CCHatRecordCell *cell = [CCHatRecordCell chatRecordCellWithTableView:tableView];
                [cell setCMessageFrame:messageFrame withSearchText:_searchBar.text];
                return cell;
            }
            else
            {
                CMessageFrame *messageFrame = messageArray.lastObject;
                CCHatRecordCell *cell = [CCHatRecordCell chatRecordCellWithTableView:tableView];
                [cell setMessageFrame:messageFrame withCount:messageArray.count];
                //                [cell setCMessageFrame:messageFrame withSearchText:_searchBar.text];ng
                return cell;
                
            }
            
        }
        else if ([obj isKindOfClass:[CGroupModel class]]) {
            CGroupModel *groupModel = (CGroupModel *)obj;
            
            static NSString *NormalCellIdentifier = @"SettingNormalCell";
            SettingNormalCell *normalCell = [tableView dequeueReusableCellWithIdentifier:NormalCellIdentifier];
            if (normalCell == nil) {
                normalCell = [[[NSBundle mainBundle] loadNibNamed:@"SettingNormalCell" owner:self options:nil] objectAtIndex:0];
            }
            if (groupModel.groupType == 1) {
                [normalCell.icon setImage:[UIImage imageNamed:@"icon-discussList"] forState:UIControlStateNormal];
            } else {
                [normalCell.icon setImage:[UIImage imageNamed:@"icon-Group"] forState:UIControlStateNormal];
            }
            
            normalCell.icon.layer.cornerRadius = 5.0f/2;
            normalCell.icon.layer.masksToBounds = YES;
            [normalCell.titleLabel setText:[NSString stringWithFormat:@"%@(%zd)",groupModel.GroupName,groupModel.UserNum]];
            normalCell.rightArrow.hidden = YES;
            NSInteger rows = [tableView numberOfRowsInSection:indexPath.section];
            
            if(indexPath.row == rows - 1){
                
                [normalCell.seperatorLine setHidden:YES];
            }
            else{
                [normalCell.seperatorLine setHidden:NO];
            }
            return normalCell;
            
        }
        else {
            CContactModel *contact = (CContactModel *)obj;
            static NSString *GroupCellIdentifier = @"GroupMenberCell";
            GroupMenberCell *groupMemberCell = [tableView dequeueReusableCellWithIdentifier:GroupCellIdentifier];
            if (groupMemberCell == nil) {
                groupMemberCell = [[[NSBundle mainBundle] loadNibNamed:@"GroupMenberCell" owner:self options:nil] objectAtIndex:0];
            }
            groupMemberCell.Arrow.hidden = YES;
            if ([contact.yuLiuZiduan3 isEqualToString:@"isKefu"] && contact.isDel == 0) {
                [groupMemberCell.icon setImage:[UIImage imageNamed:@"head-kefu"]];
            } else {
                if ([contact.UserName isEqualToString:@"我的电脑"]) {
                    [groupMemberCell.icon setImage:[UIImage imageNamed:@"icon-iMAC"]];
                }
                else
                {
                [groupMemberCell.icon sd_setImageWithURL:[NSURL URLWithString:[[CXmppRequestMgr shareInstance] DownHeadFileWithContact:contact.UserID]] placeholderImage:[UIImage imageNamed:@"80-80"]];
                }
            }
            //        [groupMemberCell.titleLabel setText:@"测试名字"];
            [groupMemberCell.titleLabel setText:contact.UserName];
            NSInteger rows = [tableView numberOfRowsInSection:indexPath.section];
            
            if(indexPath.row == rows - 1)
            {
                [groupMemberCell.seperatorLine setHidden:YES];
            } else {
                groupMemberCell.seperatorLine.hidden = NO;
            }
            return groupMemberCell;
            
        }
        
    }];
    
    [weakSelf.searchController setHeightForRowAtIndexPathCompletion:^CGFloat(UITableView *tableView, NSIndexPath *indexPath) {
        //        CMessageFrame *message = self.searchArray[indexPath.row];
        //        return message.cellHeight;
        return 55;
        
    }];
    
    [weakSelf.searchController setDidSelectRowAtIndexPathCompletion:^(UITableView *tableView, NSIndexPath *indexPath) {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        [weakSelf.searchController.searchBar endEditing:YES];
        NSArray *rowArray = weakSelf.searchController.searchSectionListArray[indexPath.section];
        id model = rowArray[indexPath.row];
        if ([model isKindOfClass:[CContactModel class]]) {
            CContactModel *contact = (CContactModel *)model;
            CHChatRoomBase *chat = [[CHChatRoomBase alloc] init];
            chat.group = nil;
            chat.member = contact;
            UINavigationController *nav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
            nav.navigationBarHidden = NO;
            self.navigationController.navigationBarHidden = YES;
            
            [nav pushViewController:chat animated:YES];
            
        } else if ([model isKindOfClass:[CGroupModel class]]) {
            CGroupModel *groupModel = (CGroupModel *)model;
            if (groupModel) {
                CHChatRoomBase *chat = [[CHChatRoomBase alloc] init];
                chat.group = groupModel;
                chat.member = nil;
                UINavigationController *nav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                nav.navigationBarHidden = NO;
                self.navigationController.navigationBarHidden = YES;
                
                [nav pushViewController:chat animated:YES];
            } else {
                
            }
            
            
        }
        else {
            NSMutableArray *messageArray = (NSMutableArray*)model;
            if (messageArray.count == 1) {
                CMessageFrame *messageFrame = messageArray.lastObject;
                CHChatRoomBase *chat = [[CHChatRoomBase alloc] init];
                if (messageFrame.message.GroupId.length>3) {
                    chat.group = [[[CGroupMgr alloc]init] loadGroup:messageFrame.message.GroupId];
                    chat.member = nil;
                }
                else
                {
                    chat.group = nil;
                    chat.member = [[[CContactMgr alloc]init] loadContactWithUserId:messageFrame.message.FriendUserId];
                }
                //            IMSearchChatRecordController *search = [[IMSearchChatRecordController alloc] init];
                //
                //            CMessageModel *mo = [self.messageMgr loadMessageWithMessageId:messageFrame.message.messageId];
                //            search.message = mo;
                //            if (messageFrame.message.GroupId) {
                //                search.group = [[[CGroupMgr alloc]init] loadGroup:messageFrame.message.GroupId];
                //                search.member = nil;
                //            } else {
                //                search.member = [[[CContactMgr alloc]init] loadContactWithUserId:messageFrame.message.FriendUserId];
                //                search.group = nil;
                //            }
                //                        NSLog(@"search的navi%@",self.searchDisplayController.searchContentsController.navigationController);
                //                        NSLog(@"自己的navi%@",self.navigationController);
                //                        [self.searchDisplayController.searchContentsController.navigationController pushViewController:search animated:YES];
                UINavigationController *nav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                
                [nav pushViewController:chat animated:YES];
                
            }
            else
            {
                WZSearchMessageResultController *searchMessageResultController = [[WZSearchMessageResultController alloc]initWithSearchText:_searchBar.text];
                searchMessageResultController.messageArray = messageArray;
                searchMessageResultController.isChatRecord = NO;
                UINavigationController *nav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                nav.navigationBarHidden = NO;
                self.navigationController.navigationBarHidden = YES;
                //bug 9530 fixed by lixu
                [nav pushViewController:searchMessageResultController animated:NO];
            }
            
        }
    }];
}



#pragma mark SearchBarDelegate
-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [self.searchBar resignFirstResponder];
}
//- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar                     // called when text starts editing
//{
//    searchBar.showsCancelButton = YES;
//    for(id cc in [_searchDisplayController.searchBar subviews])
//    {
//        if([cc isKindOfClass:[UIButton class]])
//        {
//            UIButton *btn = (UIButton *)cc;
//            [btn setTitle:@"取消"  forState:UIControlStateNormal];
//        }
//    }
//    
//}
//这里搜索的内容有点问题 只搜索联系人了 没有搜索聊天记录 8640 fixed by lixu
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    [self.MessageGroupSearchArray removeAllObjects];
    [self.searchController.searchAllFirstLetter removeAllObjects];
    [self.searchController.searchSectionListArray removeAllObjects];
    NSMutableArray *contactArray  = [NSMutableArray array];
    NSArray *contact = [[[CContactMgr alloc] init] searchContactWithSeachStr:searchText];
    if (contact.count>0) {
        [contactArray addObjectsFromArray:contact];
    }
       for ( ChatMessageListCellData *data in _listData) {
        if ([data.senderName isEqualToString:@"我的电脑"]) {
            CContactModel *modelContact = [[CContactModel alloc]init];
            modelContact.UserName = data.senderName;
            modelContact.UserID = data.MineUserId;
            [contactArray addObject:modelContact];
            break;
        }
    }
    NSArray *groupArray = [[[CGroupMgr alloc] init] searchGroupWithSeachStr:searchText withGroupType:0];
    NSArray *discussArray = [[[CGroupMgr alloc] init] searchGroupWithSeachStr:searchText withGroupType:1];
    NSArray *messageArray = [[[CMessageMgr alloc]init] searchMessageWithSearchStr:searchText];
//    NSMutableArray *searchArray = [NSMutableArray array];
    if (messageArray.count>0) {
        [self handleMessageData:messageArray];
        //bug 8640 fixed by lixu
//        for (CMessageModel *modelMessage in messageArray) {
//            if ([modelMessage.FriendUserName isEqualToString:@"我的电脑"]) {
//                CContactModel *modelContact = [[CContactModel alloc]init];
//                modelContact.UserName = modelMessage.FriendUserName;
//                modelContact.UserID = modelMessage.FriendUserId;
//                [contactArray addObject:modelContact];
//                break;
//            }
//        }
        
    }

//    [searchArray addObjectsFromArray:contactArray];
//    [searchArray addObjectsFromArray:groupArray];
//    [searchArray addObjectsFromArray:discussArray];
//    if (searchArray.count == 0 && messageArray.count == 0) {
//        return;
//    }
//    NSArray *allContactArray = [NSArray sortArray:searchArray];
    NSMutableArray *searchArrayM = [NSMutableArray array];
    if (contactArray.count>0) {
        [searchArrayM addObject:contactArray];
    }
    if (groupArray.count>0) {
        [searchArrayM addObject:groupArray];
    }
    if (discussArray.count>0) {
        [searchArrayM addObject:discussArray];
    }
    if (self.MessageGroupSearchArray.count>0) {
        [searchArrayM addObject:self.MessageGroupSearchArray];
        
    }
    
    NSMutableArray *headArray = [NSMutableArray array];
    if (contactArray.count>0) {
        [headArray addObject:@"联系人"];
    }
    if (groupArray.count>0) {
        [headArray addObject:@"群"];
    }
    if (discussArray.count>0) {
        [headArray addObject:@"讨论组"];
    }
    if (self.MessageGroupSearchArray.count > 0) {
        [headArray addObject:@"聊天记录"];
    }
    self.searchController.searchAllFirstLetter = headArray;
    self.searchController.searchSectionListArray = searchArrayM;
}
-(void)handleMessageData:(NSArray*)messages
{
    NSMutableArray *messageArray = [NSMutableArray array];
    [messages enumerateObjectsUsingBlock:^(CMessageModel *obj, NSUInteger idx, BOOL *stop) {
        
        ChatMessageListCellData *data = [[ChatMessageListCellData alloc] init];
        data.messageIndex = obj.MessageIndex;
        if (obj.GroupId.length > 3) {
            data.FriendUserId = obj.MineUserId;
            data.senderName = obj.MineUserName;
            data.headImageUri = [[CXmppRequestMgr shareInstance] DownHeadFileWithContact:obj.MineUserId];
            
        } else {
            if (obj.isMineSend) {
                data.FriendUserId = obj.MineUserId;
                data.senderName = obj.MineUserName;
                data.headImageUri = [[CXmppRequestMgr shareInstance] DownHeadFileWithContact:obj.MineUserId];
            } else {
                data.FriendUserId = obj.FriendUserId;
                data.senderName = obj.FriendUserName;
                data.headImageUri = [[CXmppRequestMgr shareInstance] DownHeadFileWithContact:obj.FriendUserId];
            }
        }
        data.content = obj.MessageContent;
        data.MineUserId = obj.MineUserId;
        data.FriendJid = obj.FriendJid;
        data.MineJid = obj.MineJid;
        data.GroupId = obj.GroupId;
        data.isRead = obj.ReadStatus;
        data.messageId = obj.MessageId;
        NSDate *date = [NSDate dateWithTimeIntervalSince1970:obj.TimeStamp.longLongValue / 1000.0];
        data.sendTime = [UIUtil timeForMessageListStyle:date];
        CMessageFrame *messageFrame = [[CMessageFrame alloc] init];
        messageFrame.message = data;
        [messageArray addObject:messageFrame];
    }];
    [self handlemessageFrame:messageArray];
}
//将同一发送者的信息归类
-(void)handlemessageFrame:(NSMutableArray*)frameArray
{
    NSMutableArray *onenameArray = [NSMutableArray array];
    CMessageFrame *firstFrame = frameArray[0];
    NSString *name  = firstFrame.message.senderName;
    for (CMessageFrame *frame in frameArray) {
        if ([frame.message.senderName isEqualToString:name]) {
            [onenameArray addObject:frame];
        }
    }
    [frameArray removeObjectsInArray:onenameArray];
    [self.MessageGroupSearchArray addObject:onenameArray];
    if (frameArray.count>0) {
        [self handlemessageFrame:frameArray];
    }
    
}
- (void)doneLoadMoreMessage
{
    
    [self.AllBaseView.tableView.header endRefreshing];
    [self.AllBaseView.tableView reloadData];
    
    [self.contactBaseView.tableView.header endRefreshing];
    [self.contactBaseView.tableView reloadData];
    
    [self.WorkBaseView.tableView.header endRefreshing];
    [self.WorkBaseView.tableView reloadData];
    
}

-(void)didBecomeActive
{
    
}

- (void)reconnectNet
{
    
    BOOL isForceQuit = [USER_DEFAULT boolForKey:ISFORCEQUIT];
    if (!isForceQuit) {
        if (![[CXmppMgr shareInstance].xmppStream isAuthenticated]) {
            [[CXmppMgr shareInstance] connect];
        } else {
            [self.AllBaseView.tableView.header endRefreshing];
            [self.AllBaseView.tableView reloadData];
            
            [self.contactBaseView.tableView.header endRefreshing];
            [self.contactBaseView.tableView reloadData];
            
            [self.WorkBaseView.tableView.header endRefreshing];
            [self.WorkBaseView.tableView reloadData];
        }
    } else {
        [self.AllBaseView.tableView.header endRefreshing];
        [self.AllBaseView.tableView reloadData];
        
        [self.contactBaseView.tableView.header endRefreshing];
        [self.contactBaseView.tableView reloadData];
        
        [self.WorkBaseView.tableView.header endRefreshing];
        [self.WorkBaseView.tableView reloadData];
    }
}

- (void)receiveNotice
{
    [self topListBtnClick:self.selectedButton];
}

- (void)loadListMessage
{
    
    //        [self.lock lock];
    NSMutableArray *arrayM = [NSMutableArray array];
    NSArray *array = [self.messageMgr loadmessageList];
    NSArray *draftArray = [self.draftMgr loadAllmessageDraft];
    
    if (draftArray.count > 0) {
        for (CMessageDraft *draft in draftArray) {
            if (draft.MessageContent.length > 0) {
                [arrayM addObject:draft];
            }
            
        }
    }
    if (array.count > 0) {
        for (CMessageModel *message in array) {
            [arrayM addObject:message];
            for (CMessageDraft *draft in draftArray) {
                if ([draft.FriendUserId isEqualToString:message.FriendUserId] && draft.MessageContent.length > 0) {
                    [arrayM removeObject:message];
                }
            }
        }
        
    }
    
    NSArray *listArray = [arrayM sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"TimeStamp" ascending:NO]]];
   
    [self handleData:listArray];
    
   
    //    [self.lock unlock];
}






//-(void)checkUpdate
//{
//
//
//}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        
        
        NSURL *url = [NSURL URLWithString:[_upDateDic objectForKey:@"updateUrl"]];
        [[UIApplication sharedApplication] openURL:url];
        if(actionSheet.tag ==2){
            exit(0);
        }
    }else{
        if(actionSheet.tag ==2){
            exit(0);
        }
        
    }
}


#pragma mark UIScrollViewDelegate Methods


- (void)chatBaseNetChanged:(NSNotification *)notice

{
    //对连接改变做出响应的处理动作。用户名或密码错误!
    NSDictionary *dic = (NSDictionary *)notice.object;
    NSNumber *resultObj = (NSNumber *)[dic objectForKey:K_XMPPLOGINSTATUS];
    NSString *error = [dic objectForKey:K_XMPPLOGINERRMSG];
    
    NSString *serError = @"";
    
    if ( [error isEqualToString:@"Socket closed by remote peer"]) {
        return;
    }
    
    
    if([resultObj boolValue])
    {
        isNetconnect = YES;
        //bug 6296 fixed by 荣则兵
    } else {
        
        if (
            [USER_DEFAULT boolForKey:ISFORCEQUIT])
        {
            
            return;
        }
        
        
        if ([error isEqualToString:@"用户名或密码错误!"]) {
            
            serError = @"用户名或密码错误";
            
            JKAlertDialog *alert2 = [[JKAlertDialog alloc]initWithTitle:nil message:@"用户名或者密码错误"];
            [alert2 addButton:Button_OK withTitle:@"重新登录" handler:^(JKAlertDialogItem *item) {
                //用户退出到登录界面必须清空#pragma mark 用户退出登录以后必须清空 [CFolderMgr shareInstance].recentlyAcc = nil；
                [CFolderMgr shareInstance].recentlyAcc = nil;
                UINavigationController *rotNav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                for (UIViewController *vc in rotNav.childViewControllers) {
                    if ([vc isKindOfClass:[LoginViewController class]]) {
                        LoginViewController *login = (LoginViewController *)vc;
                        [login setverifyStatus:NO];
                        [login setErrStatus:NO errorMsg:nil];
                        login.errTimes = 0;
                        login.isUseverifyCode = NO;
                    }
                }
                
                [rotNav popToRootViewControllerAnimated:NO];
            }];
            
            [alert2 show];
            
            
        } else if ([error isEqualToString:@"网络错误!"]) {
            serError = @"当前网络不可用，请检查您的网络设置";
        }
        else if ([error isEqualToString:@"服务器异常!"])
        {
            serError = @"与服务器断开连接";
        }
        else {
            serError = @"与服务器断开连接";
        }
        isNetconnect = NO;
    }
    
    self.AllBaseView.serError = serError;
    self.WorkBaseView.serError = serError;
    self.contactBaseView.serError = serError;
    
    self.AllBaseView.isNetconnect = isNetconnect;
    self.WorkBaseView.isNetconnect = isNetconnect;
    self.contactBaseView.isNetconnect = isNetconnect;
    
    [self.AllBaseView.tableView.header endRefreshing];
    [self.WorkBaseView.tableView.header endRefreshing];
    [self.contactBaseView.tableView.header endRefreshing];
    
    [self.AllBaseView.tableView reloadData];
    [self.WorkBaseView.tableView reloadData];
    [self.contactBaseView.tableView reloadData];
}




#pragma mark EFengChatBaseViewDelegate
- (void)EFengChatBaseViewDidCommitEditWithMessage:(ChatMessageListCellData *)listData
{
    if (listData.GroupId.length > 0) {
        
        [self.messageMgr updateMessageWithIsShowInMessageList:NO groupId:listData.GroupId];
        [self.draftMgr delMessageDraftWithFriend:listData.GroupId mineId:listData.MineUserId];
        
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"TabBadgeChangeValue" object:nil];
        
    } else {
        [self.messageMgr updateMessageWithIsShowInMessageList:NO FriendId:listData.FriendUserId MineId:listData.MineUserId];
        [self.draftMgr delMessageDraftWithFriend:listData.FriendUserId mineId:listData.MineUserId];
        
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"TabBadgeChangeValue" object:nil];
    }
    
    
    switch (self.selectedButton.tag) {
        case 300001:
        {
            [self loadListMessage];
            self.AllBaseView.messages = [_listData copy];
            if (_listData.count == 0) {
                self.noMessageView.hidden = NO;
            }
            [self.scrollView setContentOffset:CGPointMake(0, 0)];
            
        }
            break;
        case 300002:
        {
            [self loadListMessage];
            self.contactBaseView.messages = _listData;
            [self.scrollView setContentOffset:CGPointMake(HARDWARE_SCREEN_WIDTH, 0)];
            
        }
            break;
        case 300003:
        {
            [self loadListMessage];
            self.WorkBaseView.messages = _listData;
            
            [self.scrollView setContentOffset:CGPointMake(HARDWARE_SCREEN_WIDTH * 2, 0)];
            
        }
            break;
            
        default:
            break;
    }
    
}


- (void)EFengChatBaseViewDidSelectWithMessage:(ChatMessageListCellData *)listData
{
    UINavigationController *nav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    
    if (listData.GroupId.length > 0) {
        //            [[[CMessageMgr alloc] init] updateGroupMessageReadStatusWithGroupId:data.GroupId Status:YES];
        CGroupModel *Group = [self.groupMgr loadGroup:listData.GroupId];
        if (Group) {
            Group.unreadMeassage = listData.unreadNumber;
            CHChatRoomBase* chatView = [[CHChatRoomBase alloc]init];
            chatView.group = Group;
            chatView.member = nil;
            nav.navigationBarHidden = NO;
            self.navigationController.navigationBarHidden = YES;
            [nav pushViewController:chatView animated:YES];
        } else {
            [MBProgressHUD showError:@"该群不存在，或者已被删除"];
        }
        
    } else {
        //            [[[CMessageMgr alloc] init] updateMessageReadStatusWithMineUserId:data.MineUserId FriendUserId:data.FriendUserId Status:YES];
        
        CContactModel *member = [[[CContactMgr alloc] init] loadContactWithUserId:listData.FriendUserId];
        
        if (member) {
            member.unreadMeassage = listData.unreadNumber;
            __block CHChatRoomBase* chatView = [[CHChatRoomBase alloc]init];
            chatView.member = member;
            chatView.group = nil;
            if ([member.yuLiuZiduan3 isEqualToString:@"isWaibu"]) {
                [[CXmppRequestMgr shareInstance] getUserInfoWithUserCode:member.UserCode AndsuccessHandel:^(AFHTTPRequestOperation *operation, id responseObject) {
                    CCompany *newCompany = [[CCompany alloc]init];
                    newCompany.compCode = responseObject[@"companyId"];
                    newCompany.yuLiuZiduan1 = responseObject[@"companyName"];
                    [[[CCompanyMgr alloc]init] insetCompany:newCompany];
                    member.address = responseObject[@"address"];
                    member.Autograph = responseObject[@"autograph"];
                    member.birthDay = responseObject[@"birthday"];
                    member.compCode = responseObject[@"companyId"];
                    member.Telephone = responseObject[@"telephone"];
                    member.Email = responseObject[@"email"];
                    member.MobileTelephone = responseObject[@"mobilePhone"];
                    member.Position = responseObject[@"position"];
                    member.UserName = responseObject[@"realName"];
                    member.SEX = responseObject[@"sex"];
                   [[[CContactMgr alloc]init] updateContact:member];
                    chatView.member = member;
                } filarueHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
                    
                }];
            }

            //    chatView.childHoodRoom = [_roomDic objectForKey:[NSString stringWithFormat:@"%lld",data.messageRoomID]];
            //    chatView.roomName = data.senderName;
            nav.navigationBarHidden = NO;
            self.navigationController.navigationBarHidden = YES;
            [nav pushViewController:chatView animated:YES];
            
        } else {
            [MBProgressHUD showError:@"未查询到相关人员信息"];
        }
        //           /////bug6065 yh
        
    }
    
}

- (void)EFengChatBaseViewNetSectionDidClick
{
    if(IOS8){
        NSURL *url = [NSURL URLWithString:@"prefs:root=General"];
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            [[UIApplication sharedApplication] openURL:url];
        }
    }
    
}
#pragma mark chalistDelegate
- (void)eFengChatListDidSelectWithIndexPath:(NSIndexPath *)indexPath
{
    [self.chatList hieChatListView];
    switch (indexPath.row) {
        case 0:
        {
            NSArray *idArray = [_messageMgr loadAllUnReadMessgeID];
            [self chatUpdateMessageReadStatusToServiceWithArray:idArray];
            [_messageMgr updateAllMessageReadSatuWithIdArray:idArray];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"TabBadgeChangeValue" object:nil];
            [self loadListMessage];
            //bug 9525 fixed by lixu
            self.AllBaseView.messages = [_listData copy];
            [self.AllBaseView.tableView reloadData];
           
        }
            break;
            
        default:
            break;
    }
}

//向服务器发送消息的已读状态
- (void)chatUpdateMessageReadStatusToServiceWithArray:(NSArray *)array
{
    //向服务器发送消息的已读状态
//    NSString *textIds = [NSString string];
//    NSString *voiceIds = [NSString string];
//    for (CMessageModel *mesModel in array) {
//        if ([mesModel.MessageType isEqualToString:@"text"] && !mesModel.isMineSend) {
//            NSRange range = [mesModel.MessageId rangeOfString:@"-"];
//            if (range.location != NSNotFound) {
//                NSString *str = [mesModel.MessageId substringToIndex:range.location];
//                textIds = [textIds stringByAppendingFormat:@"%@,",str];
//            }
//            else
//            {
//                textIds = [textIds stringByAppendingFormat:@"%@,",mesModel.MessageId];
//            }
//        } else if ([mesModel.MessageType isEqualToString:@"voice"] && !mesModel.isMineSend){
//            NSRange range = [mesModel.MessageId rangeOfString:@"-"];
//            if (range.location != NSNotFound) {
//                NSString *str = [mesModel.MessageId substringToIndex:range.location];
//                voiceIds = [voiceIds stringByAppendingFormat:@"%@,",str];
//            }
//           else
//           {
//              voiceIds = [voiceIds stringByAppendingFormat:@"%@,",mesModel.MessageId];
//           }
//        }
//    }
//    if (textIds.length > 5) {
//        textIds = [textIds substringToIndex:textIds.length - 1];
//        [[CXmppRequestMgr shareInstance] updateMessageReadStatusWithMessageIds:textIds messageType:@"message"];
//    }
//    if (voiceIds.length > 5) {
//        voiceIds = [voiceIds substringToIndex:voiceIds.length - 1];
//        [[CXmppRequestMgr shareInstance] updateMessageReadStatusWithMessageIds:voiceIds messageType:@"voice"];
//    }
    NSString *messageIds = [NSString string];
    for (CMessageModel *mesModel in array) {
        if (!mesModel.isMineSend) {
            NSRange range = [mesModel.MessageId rangeOfString:@"-"];
            if (range.location != NSNotFound) {
            NSString *str = [mesModel.MessageId substringToIndex:range.location];
            messageIds = [messageIds stringByAppendingFormat:@"%@,",str];
            }
            else
            {
            messageIds = [messageIds stringByAppendingFormat:@"%@,",mesModel.MessageId];
            }

        }
        if (messageIds.length>5) {
            messageIds = [messageIds substringToIndex:messageIds.length - 1];
            [[CXmppRequestMgr shareInstance] updateMessageReadStatusWithMessageIds:messageIds messageType:@"message"];
        }
    }
    
}

#pragma mark
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self.chatList hieChatListView];
}

- (CGSize)ist_sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size andString:(NSString *)str{
    if ([[[UIDevice currentDevice] systemVersion] compare:@"7"] != NSOrderedAscending) {
        NSDictionary *attributes = @{NSFontAttributeName:font};
        return [str boundingRectWithSize:size options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attributes context:nil].size;
    }else{
        if (CGSizeEqualToSize(size, CGSizeZero)) {
            return [str sizeWithFont:font];
        }
        return [str sizeWithFont:font constrainedToSize:size];
    }
}
- (CGSize)ist_sizeWithFont:(UIFont *)font andString:(NSString *)str{
    return [self ist_sizeWithFont:font constrainedToSize:CGSizeZero andString:str];
}

@end
